'''
main业务的路由和视图处理函数
'''
from . import main_blueprint
import datetime
# from .. import db
from ..models import *
import cv2
from flask import render_template, request, session, redirect, Response
from gevent import monkey
monkey.patch_all
import gevent
import base64
from .. import websockets
import pickle
from socket import *
import os
import numpy as np
import json
import random
import struct
from threading import Thread
import websocket
import requests

appdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

class WSClient():
    def __init__(self,fws,fname):
        self.fname = fname
        self.fws = fws

    def test_websocket(self):
        def on_open(ws):
            ws.send(self.fname)

        def on_message(ws,message):
            self.fws.send(message)

        def on_error(ws, error):
            print(error)

        def on_close(ws):
            print("### closed ###")

        websocket.enableTrace(True)
        ws = websocket.WebSocketApp("ws://192.168.250.13:8002/progress",
                                    on_message=on_message,
                                    on_error=on_error,
                                    on_close=on_close)

        ws.on_open = on_open  
        ws.run_forever()
    
def test_ws(fws,fname):
    ws = WSClient(fws,fname)
    ws.test_websocket()

# ============================================ views =======================================================

@main_blueprint.route('/style_migration',methods=['POST',])
def sm_views():
    '''接收图片并转发至算法服务器'''
    content_img = request.files['content_img']
    style_id = request.form.get('style_id',None)
    
    url = "http://192.168.250.13:8002/style_migration"

    files = {'content_img':(content_img.filename,content_img)}
    data = {'style_id':style_id}

    res = requests.post(url,data=data,files=files)
    print(res)
    print(res.text)
    return res.content
    
@websockets.route('/getProgress')
def ws_getProgress(ws):
    '''websocket转发'''
    fname = ws.receive()
    
    # 启用一个线程做websocket转发
    t = Thread(target=test_ws,args=(ws,fname,))
    t.setDaemon(True)
    t.start()



@main_blueprint.route('/testRoute')
def testRoute_views():
    return '1234567890'












def ws_send(ws,f_dic,nowtime):
    # 编码并发送
    nowtime = str(nowtime)
    time = '%s-%s-%s %s:%s:%s' % (nowtime[0:4],nowtime[4:6],nowtime[6:8],nowtime[8:10],nowtime[10:12],nowtime[12:14])
    dic = {'time': time}
    ret, jpeg = cv2.imencode('.jpg', f_dic['image'])
    base64_data = str(base64.b64encode(jpeg))[2:-1]
    dic['img'] = base64_data
    if 'name' in f_dic:
        dic['name'] = f_dic['name']
    ws.send(json.dumps(dic))

# 尝试用websocket返回图片
@websockets.route('/get_imgs')
def test_socket(ws):
    pass
'''
    while not ws.closed:
        # 比对5秒内头像,进行筛选
        if faces_recv:
            for f_dic in faces_recv.pop(0):
                nowtime = int(datetime.datetime.now().strftime("%Y%m%d%H%M%S%f"))
                if 'name' in f_dic:
                    # known的流程
                    f_dic['similar_count'] = 0
                    f_dic['same_name_count'] = 0
                    f_dic['sended_time'] = nowtime
                    # print(f_dic['name'])
                    for f_rco_time in list(faces_rco_known):
                        dist = np.sqrt(np.sum(np.square(np.subtract(f_dic['embedding'], faces_rco_known[f_rco_time]['embedding']))))
                        if dist < 1.05:
                            f_dic['similar_count'] += 1
                            if f_dic['name'] == faces_rco_known[f_rco_time]['name']:
                                f_dic['same_name_count'] += 1
                                f_dic['sended_time'] = faces_rco_known[f_rco_time]['sended_time']
                    else:
                        # 无相像的人,或者有一个相像人,但不同名(此时判断不了哪个名是对哪个名是错,所以都要输出)
                        if f_dic['similar_count'] == 0 or (f_dic['similar_count'] == 1 and  f_dic['same_name_count'] == 0):
                            faces_rco_known[nowtime] = {'name':f_dic['name'],'embedding':f_dic['embedding'], 'sended_time':nowtime}
                            # print('known||ws_send_start....')
                            ws_send(ws,f_dic,nowtime)
                        elif f_dic['same_name_count']*2 == f_dic['similar_count']: # 如果概率是50%,也无法判断当前名字是对是错,则不输出,但是做记录
                            faces_rco_known[nowtime] = {'name':f_dic['name'],'embedding':f_dic['embedding'], 'sended_time':f_dic['sended_time']}
                        elif f_dic['same_name_count']*2 > f_dic['similar_count']: # 概率大于50%,则认为正确,判断是否输出并记录
                            if nowtime - f_dic['sended_time'] > 5000000:
                                ws_send(ws,f_dic,nowtime)
                                faces_rco_known[nowtime] = {'name':f_dic['name'],'embedding':f_dic['embedding'], 'sended_time':nowtime}
                                old_time = f_dic['sended_time']
                                for f_rco_time1 in list(faces_rco_known):
                                    if faces_rco_known[f_rco_time1]['sended_time'] == old_time:
                                        faces_rco_known[f_rco_time1]['sended_time'] = nowtime
                            else:
                                faces_rco_known[nowtime] = {'name':f_dic['name'],'embedding':f_dic['embedding'], 'sended_time':f_dic['sended_time']}
                        # 剩下的是查准概率小于50%,判定为不准确,不输出,记录
                        else:
                            faces_rco_known[nowtime] = {'name':f_dic['name'],'embedding':f_dic['embedding'], 'sended_time':f_dic['sended_time']}
                else:
                    # unknown的流程
                    # print('unknown')
                    for f_rco_time in list(faces_rco_unknown):
                        dist = np.sqrt(np.sum(np.square(np.subtract(f_dic['embedding'], faces_rco_unknown[f_rco_time]['embedding']))))
                        if dist < 1.05:
                            if nowtime - faces_rco_unknown[f_rco_time]['sended_time'] > 5000000:
                                faces_rco_unknown[nowtime] = {'sended_time':nowtime,'embedding': f_dic['embedding']}
                                # print('dist:',dist,nowtime,faces_rco_unknown[f_rco_time]['sended_time'])
                                old_time = faces_rco_unknown[f_rco_time]['sended_time']
                                for f_rco_time1 in list(faces_rco_unknown):
                                    if faces_rco_unknown[f_rco_time1]['sended_time'] == old_time:
                                        # print('reset...sended_time')
                                        faces_rco_unknown[f_rco_time1]['sended_time'] = nowtime
                                ws_send(ws,f_dic,nowtime)
                                break
                            else:
                                faces_rco_unknown[nowtime] = {'sended_time':faces_rco_unknown[f_rco_time]['sended_time'],'embedding': f_dic['embedding']}
                                break
                    else:
                        faces_rco_unknown[nowtime] = {'embedding':f_dic['embedding'], 'sended_time':nowtime}
                        print('无相似unknown||ws_send_start....')
                        ws_send(ws,f_dic,nowtime)
        gevent.sleep(0.02)
        '''
        
@websockets.route('/get_imgs_test')
def test_socket_test(ws):
    global appdir
    while not ws.closed:
        pic_name = random.choice(('men.jpg','female.png'))
        name = random.choice(('Philip', None, None, 'Gao', 'Jhone', 'Toey'))
        dic = {'time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
        if name:
            dic['name'] = name
        file_name = os.path.join(appdir,'static/images/index',pic_name)
        with open(file_name, 'rb') as f:
            base64_data = str(base64.b64encode(f.read()))[2:-1]
            dic['img'] = base64_data
        try:
            ws.send(json.dumps(dic))
        except Exception:
            return
        gevent.sleep(1)